package com.haocang.szgm.ui.event.acitvity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.esri.android.map.GraphicsLayer;
import com.esri.android.map.event.OnSingleTapListener;
import com.esri.core.geometry.Point;
import com.esri.core.map.Graphic;
import com.esri.core.symbol.PictureMarkerSymbol;
import com.haocang.szgm.R;
import com.haocang.szgm.activity.comm.CommMapFinalActivity;
import com.haocang.szgm.activity.tool.CacheActivityUtil;
import com.haocang.szgm.requestcenter.DataModel;
import com.haocang.commonlib.network.interfaces.InitDataBeanBack;
import com.haocang.szgm.ui.event.adapter.EventListAdapter;
import com.haocang.szgm.ui.event.bean.EventBean;
import com.haocang.szgm.utils.bean.ProvinceBean;
import com.haocang.szgm.utils.config.Config;
import com.haocang.szgm.utils.config.WebApi;
import com.haocang.commonlib.recyclerView.BaseAdapter;
import com.haocang.szgm.utils.tools.CacheData;
import com.haocang.szgm.utils.tools.MyTextUtils;
import com.haocang.szgm.utils.tools.OptionsItemsUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import net.tsz.afinal.annotation.view.ViewInject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EventActivity extends CommMapFinalActivity {

    @ViewInject(id = R.id.tv_map_addpoint)
    TextView tv_map_addpoint;

    @ViewInject(id = R.id.map_lin)
    RelativeLayout map_lin;
    @ViewInject(id = R.id.list)
    LinearLayout list;

    @ViewInject(id = R.id.et_year)
    EditText et_year;
    @ViewInject(id = R.id.tv_status)
    TextView tv_status;
    @ViewInject(id = R.id.tv_reason)
    TextView tv_reason;
    @ViewInject(id = R.id.bt_quert)
    Button bt_quert;

    @ViewInject(id = R.id.refreshLayout)
    RefreshLayout refreshLayout;
    @ViewInject(id = R.id.recyclerview)
    RecyclerView recyclerview;

    private EventListAdapter mAdapter;

    protected GraphicsLayer gEventLayer;//自定义图层
    private Map<Integer, EventBean> mLocationMapList;


    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CacheActivityUtil.addActivity(EventActivity.this);
        context = EventActivity.this;
        initView();

        initEvent();

        refreshLayout.autoRefresh();

    }

    @Override
    public void onResume() {
        super.onResume();
        if(refreshLayout!= null){
            refreshLayout.autoRefresh();
        }
    }

    @Override
    protected int getLayoutResourceId() {
        return R.layout.activity_event_list;
    }

    @Override
    protected boolean showNavigation() {
        return true;
    }

    @Override
    protected boolean showMedia() {
        return false;
    }

    @Override
    protected int showMoreIcon() {
        return R.drawable.ic_map;
    }

    @Override
    protected String showTitleName() {
        return "事件";
    }

    @Override
    protected boolean showMapPipe() {
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CacheActivityUtil.finishSingleActivity(EventActivity.this);
    }

    private void initView() {
        gEventLayer = new GraphicsLayer();
        mMapView.addLayer(gEventLayer);
        mLocationMapList = new HashMap<>();

        mAdapter = new EventListAdapter(EventActivity.this);
        recyclerview.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL) {
            @Override
            public boolean canScrollVertically() {
                return true;//是否允许滑动
            }
        });
        recyclerview.setAdapter(mAdapter);

    }


    private void initEvent() {

        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
            }

        });

        iv_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (list.getVisibility() == View.GONE) {
                    list.setVisibility(View.VISIBLE);
                    map_lin.setVisibility(View.GONE);
                    list.setAnimation(AnimationUtils.makeInAnimation(mContext, true));
                    map_lin.setAnimation(AnimationUtils.makeOutAnimation(mContext, true));
                    iv_more_icon.setBackgroundResource(R.drawable.ic_map);
                } else {
                    list.setVisibility(View.GONE);
                    map_lin.setVisibility(View.VISIBLE);
                    list.setAnimation(AnimationUtils.makeOutAnimation(mContext, false));
                    map_lin.setAnimation(AnimationUtils.makeInAnimation(mContext, false));
                    iv_more_icon.setBackgroundResource(R.drawable.ic_list);
                }
            }

        });


        tv_status.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseDeviceCode(OptionsItemsUtils.GetEventStatus(),1);
            }

        });

        tv_reason.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseDeviceCode(OptionsItemsUtils.GetAllReasonList(),2);
            }

        });

        bt_quert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshLayout.autoRefresh();
            }

        });


        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                Config.PAGE_LIMIT = Config.PAGE_SHOW_LIMIT;
                refreshlayout.finishRefresh(20000/*,false*/);//传入false表示刷新失败
                initData(refreshlayout);
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadmore(20000/*,false*/);//传入false表示加载失败
                Config.PAGE_LIMIT += Config.PAGE_SHOW_LIMIT;
                initData(refreshlayout);
            }
        });

        mAdapter.setOnItemChildClickListener(new BaseAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseAdapter adapter, View v, int position) {
                EventBean model = mAdapter.getItem(position);
                Intent intent = new Intent(EventActivity.this, EventDetailActivity.class);
                CacheData.mEventBean = model;
                CacheData.Event_UPDATE = true;
                startActivity(intent);
            }

        });

        mMapView.setOnSingleTapListener(new OnSingleTapListener() {
            @Override
            public void onSingleTap(float x, float y) {

                int[] ids = gEventLayer.getGraphicIDs(x, y, 5);
                if (ids.length > 0) {
                    final EventBean mEventpoint = mLocationMapList.get(ids[0]);

                    CacheData.Event_UPDATE = true;
                    CacheData.mEventBean = mEventpoint;
                    Intent intent = new Intent(EventActivity.this, EventDetailActivity.class);
                    startActivity(intent);

                } else {

                    Point mapPoint = mMapView.toMapPoint(x, y);
                    SingleTap_X = mapPoint.getX();
                    SingleTap_Y = mapPoint.getY();
                    addpoint(mapPoint, R.mipmap.icon_point_01);
                }
            }
        });


        tv_map_addpoint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (SingleTap_X == 0 || SingleTap_Y == 0) {
                    ToastShow("请在地图上设置事件位置");
                    return;
                }
                //跳转到积水明细上报界面
                CacheData.Event_UPDATE = false;
                CacheData.mEventBean = null;
                Intent intent = new Intent(EventActivity.this, EventDetailActivity.class);
                intent.putExtra("X", SingleTap_X);
                intent.putExtra("Y", SingleTap_Y);
                startActivity(intent);
            }
        });

    }


    private void  initData(final RefreshLayout refreshlayout) {
        String year  = et_year.getText().toString();
        String status  = MyTextUtils.GetOpitemValue(OptionsItemsUtils.GetEventStatus(),0,tv_status.getText().toString());
        String reason  = MyTextUtils.GetOpitemValue(OptionsItemsUtils.GetAllReasonList(),0,tv_reason.getText().toString());

        String ApiUrl = Config.host
                + WebApi.Api_Event
                +"?limit="+ Config.PAGE_LIMIT
                +"&year="+year
                +"&status="+status
                +"&WarningID="+reason;

        DataModel.GetApiRequestMode("EventBean", ApiUrl, new InitDataBeanBack<EventBean>() {
            @Override
            public void callbak(boolean b, List<EventBean> list , String msg) {
                if(b){
                    mAdapter.setNewData(list);
                    MarkPoint(list);
                    refreshlayout.finishRefresh(true);//刷新完成
                    refreshlayout.finishLoadmore(true);
                }else{
                    ToastShow(msg);
                    refreshlayout.finishRefresh(false);
                    refreshlayout.finishLoadmore(false);
                }
            }
        });
    }

    private void MarkPoint(final List<EventBean> list){
        gEventLayer.removeAll();
        mLocationMapList.clear();
        for(EventBean m :list){

            int icon=0;
            if(m.getStatus() == 0){
                icon = R.mipmap.map_shijian_r;
            }else  if(m.getStatus() == 1){
                icon = R.mipmap.map_shijian_y;
            }else{
                icon = R.mipmap.map_shijian_g;
            }

            PictureMarkerSymbol locationSymbol = new PictureMarkerSymbol(context.getResources().getDrawable(icon));
            Graphic graphic = new Graphic(new Point(m.getXLng(),m.getYLat()), locationSymbol);
            mLocationMapList.put(gEventLayer.addGraphic(graphic),m);
        }
    }


    private void chooseDeviceCode(final List<ProvinceBean> items, final int pos) {
        OptionsPickerView.Builder builder = new OptionsPickerView.Builder(context, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String itemName = items.get(options1).getPickerViewText();
                switch (pos) {
                    case 1:
                        tv_status.setText(itemName);
                        break;
                    case 2:
                        tv_reason.setText(itemName);
                        break;
                }
            }
        });
        OptionsPickerView<ProvinceBean> pickerView = new OptionsPickerView<>(builder);
        pickerView.setPicker(items);
        pickerView.show();
    }

}
